<script setup>
import Dialog from '@vant/weapp/dist/dialog/dialog';
import Toast from '@vant/weapp/dist/toast/toast';

import { getCategoryList } from '@/api/home'
import { getAiImgRecordList, delAiImgRecord, getImageByTaskId } from '@/api/painting';
import { usePaintingStore } from '@/store';

import { ref, onMounted, nextTick, computed, watch } from 'vue'



const props = defineProps({
    isDownload: {
        type: Boolean,
        default: false
    }
})


const paintingStore = usePaintingStore()



const queryParams = ref({
    page: 0,
    pageSize: 10,
    type: 1,
    status: 0
})
// tabs列表
const tabsList = ref([])
// tabs当前选中
const current = ref(0)
// 是否展开tab选择框
const isTabsShow = ref(false)

// 获取tab实例
const tabsRef = ref(null)
// 历史记录列表
const recordList = ref([[], []])
const flag = ref(true)
// 任务Id
const taskId = ref('')
// 滚动位置
const scrollTop = ref(0)

const isAllText = computed(() => {
    if (recordList.value.every(group => group.length === 0)) {
        return '全选';
    }
    const allSelected = recordList.value.every(group => group.every(item => item.checked));
    return allSelected ? '取消' : '全选';
});



// 定义触摸起始点的坐标
let startX, startY = 0;
let endX, endY = 0;


watch(() => props.isDownload, (newVal) => {
    if (newVal) {
        recordList.value.forEach(group => {
            group.forEach(item => {
                item.checked = false; // 重置选中状态
            });
        });
    }
}, { immediate: true, deep: true })


// 全选
function isAllFn() {
    if (recordList.value.every(group => group.length === 0)) return Toast.fail('暂无数据')
    const allSelected = recordList.value.every(group => group.every(item => item.checked));
    recordList.value.forEach(group => {
        group.forEach(item => {
            item.checked = !allSelected;
        });
    });
}

// 删除图片
async function clearImgFn() {
    // 获取选中的图片
    const selectedItems = recordList.value.flat().filter(item => item.checked);
    if (!selectedItems.length) return Toast.fail('请先选择要删除的图片')
    uni.showModal({
        title: '提示',
        content: '是否删除选中的图片？',
        success: async (res) => {
            if (res.confirm) {
                const ids = selectedItems.map(item => item.id)
                await delAiImgRecord(ids)
                Toast.success('删除成功')
                flag.value = true
                queryParams.value.page = 0
                getAiImgRecordListFn()
            }
        }
    })
}




// 下载图片
function downloadFn(e) {
    const imgPath = e.imgPath.split(';')
    paintingStore.accredit({ path: imgPath })
}



// 触摸开始事件处理函数
function onTouchStart(event) {
    // 获取触摸起始点的X和Y坐标
    startX = event.touches[0].clientX;
    startY = event.touches[0].clientY;
}

// 触摸移动事件处理函数
function onTouchMove(event) {
    // 获取触摸移动后的X和Y坐标
    endX = event.touches[0].clientX;
    endY = event.touches[0].clientY;
}

// 触摸结束事件处理函数
function onTouchEnd() {
    // 计算触摸滑动的水平和垂直距离
    const deltaX = endX - startX;
    const deltaY = endY - startY;

    // 判断是否为左右滑动且滑动距离足够
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 75) {
        if (deltaX > 0 && current.value > 0) {
            // 右滑，切换到前一个tab
            current.value--;
        } else if (deltaX < 0 && current.value < tabsList.value.length - 1) {
            // 左滑，切换到下一个tab
            current.value++;
        }
        // 调用tabsChange方法以更新当前选中的tab
        tabsChange({ detail: { index: current.value } });
    }

    // 重置触摸坐标
    startX = startY = endX = endY = 0;
}


// 获取任务状态
async function getImageByTaskIdFn() {
    Toast.loading({
        message: '状态获取中...',
        forbidClick: true,
        duration: 0,
    });
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        Toast.success('获取成功')
        queryParams.value.page = 0
        flag.value = true
        getAiImgRecordListFn()
    } else if ([3, 4].includes(res.data.state)) {
        Toast.fail('正在生成中')
    } else {
        Toast.fail('生成失败')
    }
}



// 更新图片状态
function upadteImgState(e) {
    const title = tabsList.value[current.value]?.title
    if (props.isDownload) {
        return e.checked = !e.checked
    }
    if (e.state === 1) {
        if (queryParams.value.type === 13) {
            e.title = `绘图历史-${title}`
            uni.navigateTo({
                url: `/newEditionDraw/imgCreateText/detail/index?data=${JSON.stringify({ id: e.id, title: e.title })}`,
            });
        } else if (queryParams.value.type === 29) {
            e.title = `绘图历史-${title}`
            uni.navigateTo({
                url: `/newEditionDraw/aiVideo/detail/index?item=${JSON.stringify({ id: e.id, title: e.title })}`,
            });
        } else {
            e.title = `绘图历史-${title}`
            uni.navigateTo({
                url: `/draw/paintingResultPage/index?item=${JSON.stringify({ id: e.id, title: e.title })}`,
            });
        }
    } else if ([3, 4].includes(e.state)) {
        taskId.value = e.taskId
        getImageByTaskIdFn()
    }

}


// tabs切换
function tabsChange(e) {
    current.value = e.detail.index
    queryParams.value.type = tabsList.value[current.value]?.modelTypeId
    flag.value = true
    queryParams.value.page = 0
    getAiImgRecordListFn()
    scrollTop.value = Math.random() * 0.1
}

// tabs切换
function newTabsChange(index) {
    current.value = index
    setTimeout(() => {
        isTabsShow.value = false
    }, 600)
}

// 获取历史记录列表
async function getAiImgRecordListFn() {
    if (!flag.value) return
    const res = await getAiImgRecordList(queryParams.value)
    if (queryParams.value.page === 0) {
        recordList.value = [[], []] // 初始化为左右两个数组
    }
    if (res.data.length >= 10) {
        queryParams.value.page++
    } else {
        flag.value = false
    }

    res.data.forEach((item, index) => {
        if (item.imgTempPath) {
            item._imgPath = item.imgTempPath.split(';') || []
        } else if (item.imgPath) {
            item._imgPath = item.imgPath.split(';') || []
        } else {
            item._imgPath = []
        }


        // 根据索引将数据分配到左右两个数组
        recordList.value[index % 2].push(item)
    })
}


// 获取tabs列表
async function getCategoryListFn() {
    const res = await getCategoryList(10)
    tabsList.value = res.data
    queryParams.value.type = tabsList.value[0]?.modelTypeId
    nextTick(() => {
        tabsRef.value?.resize()
    })
}


// 滚动到底部
function onScrolltolower() {
    getAiImgRecordListFn()
}


onMounted(async () => {
    await getCategoryListFn()
    getAiImgRecordListFn()
})

const tabTitleStyle = {
    width: '300rpx !important',
}
</script>

<template>
    <div class='aiDraw'>
        <div class="tabs_box">
            <div class="left">
                <van-tabs ref="tabsRef" :active="current" @change="tabsChange" line-width="12" line-height="3"
                    title-active-color="var(--a-one-text-color)" title-inactive-color="var(--a-two-text-color)"
                    color="var(--a-main-color)" :tab-class="tabTitleStyle">
                    <van-tab :title="item?.title" v-for="item of tabsList" :key="item.id"></van-tab>
                </van-tabs>
            </div>
            <div class="right" @click="isTabsShow = !isTabsShow">
                <i class="iconfont ai-icon-xiantiaoshangsanjiao" v-if="!isTabsShow"></i>
                <i class="iconfont ai-icon-close" v-else></i>
            </div>
            <div class="tabsContent" :class="{ show: isTabsShow }">
                <div class="c_Tabs">
                    <div class="c_tab" :class="{ active: current === index }" v-for="item, index of tabsList" :key="item.id"
                        @click="newTabsChange(index)">
                        {{ item?.title }}
                    </div>
                </div>
            </div>
        </div>

        <scroll-view scroll-y :scroll-top="scrollTop" class="scrollView" @scrolltolower="onScrolltolower"
            @touchstart="onTouchStart" @touchmove.stop="onTouchMove" @touchend="onTouchEnd">
            <div class="scroll_item" v-if="recordList[0].length || recordList[1].length">
                <div class="left_box">
                    <div class="img_box" v-for="item, index of recordList[0]" :key="index" @click="upadteImgState(item)">
                        <img v-if="item?.state === 1" :src="item?._imgPath[0]" class="imgSty" alt="" mode="widthFix"
                            lazy-load>
                        <img v-if="item?.state !== 1" :src="item?.orgImgPath" class="imgSty" mode="widthFix" lazy-load>
                        <!-- 生成失败 -->
                        <div v-if="item?.state !== 1 && ![3, 4].includes(item?.state)" class="imgFail">
                            <p class="title">生成失败了</p>
                            <p class="content">换个提示词或重新生成试试吧</p>
                            <p class="content">算力值已返回账户</p>
                        </div>

                        <!-- 生成中 -->
                        <div v-if="item?.state !== 1 && [3, 4].includes(item?.state)" class="imgInCreate">
                            <div class="title">创作生成中...</div>
                            <div class="refresh">
                                <i class="iconfont ai-icon-zhongxinshengcheng"></i>
                                点击刷新
                            </div>
                        </div>

                        <!-- 下载按钮 -->
                        <div v-if="item?.state === 1 && !isDownload && queryParams.type !== 29" class="download"
                            @touchend="downloadFn(item)" @click.stop>
                            <i class="iconfont ai-icon-xiazai"></i>
                        </div>

                        <!-- 选中 -->
                        <checkbox v-if="isDownload" class="checkboxClass" :value="item.id" :checked="item.checked">
                        </checkbox>
                    </div>
                </div>
                <div class="right_box">
                    <div class="img_box" v-for="item, index of recordList[1]" :key="index" @click="upadteImgState(item)">
                        <img v-if="item?.state === 1" :src="item?._imgPath[0]" class="imgSty" alt="" mode="widthFix"
                            lazy-load>
                        <img v-if="item?.state !== 1" :src="item?.orgImgPath" class="imgSty" mode="widthFix" lazy-load>

                        <!-- 生成失败 -->
                        <div v-if="item?.state !== 1 && ![3, 4].includes(item?.state)" class="imgFail">
                            <p class="title">生成失败了</p>
                            <p class="content">换个提示词或重新生成试试吧</p>
                            <p class="content">算力值已返回账户</p>
                        </div>

                        <!-- 生成中 -->
                        <div v-if="item?.state !== 1 && [3, 4].includes(item?.state)" class="imgInCreate">
                            <div class="title">创作生成中...</div>
                            <div class="refresh">
                                <i class="iconfont ai-icon-zhongxinshengcheng"></i>
                                点击刷新
                            </div>
                        </div>

                        <!-- 下载按钮 -->
                        <div v-if="item?.state === 1 && !isDownload && queryParams.type !== 29" class="download"
                            @touchend="downloadFn(item)" @click.stop>
                            <i class="iconfont ai-icon-xiazai"></i>
                        </div>

                        <!-- 选中 -->
                        <checkbox v-if="isDownload" class="checkboxClass" :value="item.id" :checked="item.checked">
                        </checkbox>
                    </div>
                </div>
            </div>
            <img v-else class="noData" src="@/draw/assets/暂无数据.png" mode="aspectFill">
        </scroll-view>


        <div class="footer" v-if="isDownload">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <div class="left" @click="isAllFn">{{ isAllText }}</div>
                <div class="right" @click="clearImgFn">删除</div>
            </div>
        </div>
        <!-- 遮罩层 -->
        <div class="overlay" v-if="isTabsShow" @click="isTabsShow = false"></div>
    </div>
</template>

<style lang='scss' scoped>
.aiDraw {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .tabs_box {
        box-sizing: border-box;
        position: relative;
        height: 90rpx;
        z-index: 2;
        background-color: #131130;
        padding: 0 30rpx;
        display: flex;
        align-items: center;

        &::after {
            content: '';
            position: absolute;
            top: 0;
            right: 70rpx;
            z-index: 1;
            width: 200rpx;
            height: 100%;
            background: linear-gradient(to left, #131130, rgba(255, 255, 255, 0));
            pointer-events: none;
            /* 允许点击穿透 */
        }

        .left {
            box-sizing: border-box;
            flex: 1;
            height: 100%;
            overflow: hidden;
        }

        .right {
            flex-shrink: 0;
            width: 60rpx;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: flex-end;

            .iconfont {
                font-size: 32rpx;
                color: var(--a-one-text-color);
            }
        }

        .tabsContent {
            box-sizing: border-box;
            position: absolute;
            top: 90rpx;
            left: 0;
            width: 100%;
            height: 0;
            background-color: #131130;
            overflow: hidden;
            transition: all 0.3s ease-in-out;
            padding: 0 30rpx;

            &.show {
                height: 500rpx;
            }

            .c_Tabs {
                display: grid;
                grid-template-columns: repeat(5, 1fr);
                gap: 13rpx;
                margin-top: 30rpx;

                .c_tab {
                    box-sizing: border-box;
                    height: 76rpx;
                    border-radius: 12rpx;
                    color: var(--a-one-text-color);
                    background: var(--a-adapter-bg-color);
                    font-size: 24rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    text-align: center;

                    &.active {
                        color: var(--a-main-color);
                        border: 2rpx solid var(--a-main-color);
                    }
                }
            }
        }

    }



    .scrollView {
        flex: 1;
        height: 1rpx;
        margin-top: 20rpx;
        padding-bottom: 40rpx;
        position: relative;

        .noData {
            display: block;
            width: 500rpx;
            height: 500rpx;
            position: absolute;
            top: 40%;
            left: 50%;
            transform: translate(-50%, -50%);

        }

        .scroll_item {
            box-sizing: border-box;
            padding: 0 30rpx;
            display: flex;
            align-items: flex-start;
            gap: 20rpx;

            .left_box {
                box-sizing: border-box;
                flex: 1;
                flex-shrink: 0;
                height: 100%;
                display: flex;
                flex-direction: column;
                gap: 20rpx;
            }

            .right_box {
                box-sizing: border-box;
                flex: 1;
                flex-shrink: 0;
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                gap: 20rpx;
            }

            .img_box {
                position: relative;

                .imgSty {
                    width: 100%;
                    border-radius: 24rpx;
                    background-color: rgba($color: #ffffff, $alpha: 0.1);
                }

                .imgFail,
                .imgInCreate {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    color: var(--a-one-text-color);
                    background-color: rgba(0, 0, 0, 0.65);
                    border-radius: 24rpx;

                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;

                    .title {
                        font-size: 32rpx;
                        margin-bottom: 24rpx;
                    }

                    .content {
                        font-size: 22rpx;
                        line-height: 38rpx;
                    }

                    .refresh {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        font-size: 24rpx;

                        .iconfont {
                            margin-right: 5rpx;
                        }
                    }
                }

                .download {
                    position: absolute;
                    bottom: 15rpx;
                    right: 15rpx;
                    width: 50rpx;
                    height: 50rpx;
                    border-radius: 50%;
                    background: rgba(0, 0, 0, 0.65);
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .iconfont {
                        font-size: 34rpx;
                        color: var(--a-one-text-color);
                    }
                }

                .checkboxClass {
                    position: absolute;
                    bottom: 15rpx;
                    right: 15rpx;
                }
            }

        }

    }


    .overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1;
    }

    .footer {
        .footer_placeholder {
            height: 170rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 170rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx 0;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            gap: 16rpx;

            .left,
            .right {
                flex: 1;
                flex-shrink: 0;
                height: 84rpx;
                border-radius: 42rpx;
                display: flex;
                align-items: center;
                justify-content: center;

                &.left {
                    // color: var(--a-main-color);
                    // border: 1rpx solid var(--a-main-color);
                    color: var(--a-one-text-color);
                    border: 2rpx solid #45426f;
                }

                &.right {
                    // color: var(--a-one-text-color);
                    // background: var(--a-main-color);
                    color: var(--a-mod-bg-color);
                    background: linear-gradient(90deg, #C3E9FF 0%, #A3B4FA 100%);

                }
            }

        }
    }
}
</style>